# -*- coding: utf_8 -*-
# @Time : 2021/8/10 0010 16:45
# @Author : lyw
# @Remark : 数据源db
import logging

from mxsoftpy import DB
from mxsoftpy.exception import DBError

from db.common.IOTManager.Janitor.janitor_base import JanitorBase
from utils.classes.custom_exception import VerifyError
from index import _


class DataOriginDB(DB):

    def get_origin_model(self):
        """获取品牌模板"""
        result_list = []
        try:
            for key, value in self.tree.open("Janitor", "data_origin_conf", file="IOT").sub_items().items():
                value["id"] = key
                result_list.append(value)
        except DBError as e:
            logging.error(e)
            raise VerifyError(_("查询错误"))
        return result_list


class ADDDataOriginDB(JanitorBase):

    def create(self, **kwargs):
        """
        插入
        @param kwargs: model 中验证
        @return:
        """
        # return self.open("Janitor", "data_origin", file="IOT").insert_key_items(
        #     [(k, v) for k, v in kwargs.items()])
        try:
            self.tree.open("Janitor", "data_origin", file="IOT")
            self.tree.begin()
            sub_key = self.tree.insert_sub_keys("")
            self.tree.open("Janitor", "data_origin" + "\\" + sub_key, file="IOT").insert_items(
                [(k, v) for k, v in kwargs.items()])
        except DBError as e:
            logging.error(e)
            self.tree.rollback()
            raise VerifyError(_("增加失败"))
        self.tree.commit()
        logging.info("新增一条数据源 id 为:%s" % sub_key)
        return sub_key

    def update(self, sub_key, **kwargs):
        """
        更新
        @param sub_key: 数据源的子健
        @param kwargs:  插入的数据
        @return:
        """

        try:
            self.tree.open("Janitor", "data_origin" + "\\" + sub_key, file="IOT")
            self.tree.begin()
            self.tree.insert_items([(k, v) for k, v in kwargs.items()])
        except DBError as e:
            logging.error(e)
            self.tree.rollback()
            raise VerifyError(_("增加失败"))
        self.tree.commit()
        logging.info("新增一条数据源 id 为:%s" % sub_key)
        return sub_key


class GetDataOriginDB(DB):

    def get_origin_data(self, paging, **kwargs):
        """ 数据源页显示 """

        """ 筛选出要查询的数据 """
        sel = self.tree.open("Janitor", 'data_origin', file="IOT")
        pro_list = ['label', 'model_id', 'desc', 'state', 'count', "type_id"]
        if kwargs['state'] == 2:
            origin_key_list = sel.filter(label__like='*' + kwargs['search'] + "*",
                                         is_del=0, **paging)
        else:
            origin_key_list = sel.filter(label__like='*' + kwargs['search'] + "*",
                                         is_del=0, state=kwargs['state'], **paging)
        origin_data_dict = sel.sub_items(key_list=origin_key_list[1], prop_list=pro_list) if origin_key_list[1] else {}

        """ 生成额外属性 """
        origin_data_conf = self.extra_data()

        data_list = []
        page = {}
        """ 修正数据属性 """
        for r_key, r_data in origin_data_dict.items():
            r_data['origin_conf_name'] = origin_data_conf[r_data['model_id']]['label']
            if type(r_data) is dict:
                # r_data['origin_id'] = r_key
                origin_id = str(r_key).rsplit(".", 1)
                r_data['origin_id'] = origin_id[1] if len(origin_id) >= 2 else r_key
                data_list.append(r_data)
            else:
                page[r_key] = r_data
        if page:
            data_list.append(page)

        """origin_key_list[0] 为总条数，data_list为当前页具体数据"""
        return origin_key_list[0], data_list

    def extra_data(self):
        """
        额外参数
        @return:
        """
        try:
            origin_data_conf = self.tree.open("Janitor", 'data_origin_conf', file="IOT").sub_items(prop_list=['label'])
        except DBError as e:
            logging.error(e)
            raise VerifyError(_("查询错误"))
        return origin_data_conf


class SelectDataOriginDB(DB):

    def update_state(self, *args):
        """
        更新状态
        @param args:
        @return:
        """
        sub_keys = self.tree.open("Janitor", 'data_origin', file="IOT").sub_keys()
        if args[0] not in sub_keys:
            return f'{args[0]}-无此任务'
        sel = self.tree.open("Janitor", f'data_origin\\%s' % args[0], file="IOT")

        if args[1] == 'is_del' and sel.fetchone_value('is_del') != 1:
            door_keys = self.tree.open("Janitor", 'door', file="IOT").filter(origin_id=args[0], is_del=0)
            for i in door_keys[1]:
                self.tree.open("Janitor", 'door\\%s' % i, file="IOT") \
                    .insert_item(prop=args[1], value=args[2], value_type='int')
            return self.tree.open("Janitor", 'data_origin\\%s' % args[0], file="IOT") \
                .insert_items(items=[(args[1], args[2]), ('state', 0)])
        elif sel.fetchone_value('state') != args[2] and sel.fetchone_value('is_del') != 1:
            return sel.insert_item(prop=args[1], value=args[2])

        return f'{args[0]}-无需修改或已被删除'


class EchoOriginDB(JanitorBase):

    def query_door(self, **kwargs):
        """
        查找门禁
        @param kwargs:
        @return:
        """
        _, data_origin = self.tree.open("Janitor", "door", file="IOT").filter(**kwargs)
        res_list = []
        for i in data_origin:
            data_info = self.tree.open("Janitor", "door\\%s" % i, file="IOT").items(
                prop_list=["auth_method", "host", "label", "model_id", "origin_id", "rec_id"])
            data_origin = self.query_host(data_origin=data_info["origin_id"])[1]
            print(data_origin)
            brand_data, brand_sub_data = self.query_brand(data_origin["model_id"])
            data_info["brand"] = brand_data["label"]
            data_info["auth_method"] = ",".join(
                [brand_sub_data["auth_method"][i] if brand_sub_data["auth_method"].get(i) else "" for i in
                 data_info["auth_method"].split(",") if i != ""])
            res_list.append(data_info)
            rec_id = str(data_info["rec_id"]).rsplit(".", 1)
            data_info["rec_id"] = rec_id[1] if len(rec_id) >= 2 else data_info["rec_id"]

            data_info["id"] = i
        return res_list


class GetConfigFieldDB(EchoOriginDB):
    pass
